package com.github.permissiondog.cancanpbackend.servlet;

import com.github.permissiondog.cancanpbackend.request.ApplicationCreateRequest;
import com.github.permissiondog.cancanpbackend.request.ApproveApplicationRequest;
import com.github.permissiondog.cancanpbackend.response.ApplicationResponse;
import com.github.permissiondog.cancanpbackend.response.ApplicationsResponse;
import com.github.permissiondog.cancanpbackend.response.BaseResponse;
import com.github.permissiondog.cancanpbackend.response.ProgressResponse;
import com.github.permissiondog.cancanpbackend.service.ApplicationService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@WebServlet("/approver/application")
public class ApproverApplicationServlet extends BaseServlet {
    /**
     * 获取申请列表
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            var apps = ApplicationService.getInstance().getApplicationsByApproverId(
                    userLoggedIn(req).getId()
            );
            json(resp, ApplicationsResponse.builder().ok(true).applications(apps).build());
        } catch (Exception e) {
            json(resp, BaseResponse.builder().ok(false).error(e.getMessage()).build());
        }
    }

    /**
     * 同意/拒绝申请
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            var body = bind(req, resp, ApproveApplicationRequest.class);
            var app = ApplicationService.getInstance().getApplicationById(body.applicationId);
            if (app == null) {
                json(resp, BaseResponse.builder().ok(false).msg("应用不存在").build());
                return;
            }
            var progress = ApplicationService.getInstance().approve(
                    body.applicationId, userLoggedIn(req).getId(),
                    body.approve, body.opinion
            );
            json(resp, ProgressResponse.builder().ok(true).progress(progress).build());
        } catch (Exception e) {
            json(resp, BaseResponse.builder().ok(false).msg("同意/拒绝申请失败").error(e.getMessage()).build());
        }
    }
}
